import 'dart:convert';

import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_attention_widget/special_attention_staff_list_view.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_filter_button_widget.dart';
import 'package:e_reception_flutter/ui/company/company_switch/bean/company_switch_list_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/utils/cache_util.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';

import 'bean/independent_company_basic_info_bean.dart';
import 'bean/independent_company_basic_info_bean.dart';
import 'event/refresh_company_detail_page_event.dart';

class CompanyDetailViewModel extends BaseViewModel {
  static const String TOP_GROUP_INFO_API =
     ServerApi.BASE_URL + "app/appCompanyHomePage";
  static const String TOP_COMPANY_INFO_API =
     ServerApi.BASE_URL + "app/appCompanyBasicInfo";

  ///获取该账号所属机构
  static const String SEARCH_ORGANIZATION_API =
     ServerApi.BASE_URL + "/app/searchOrganization";

  ///获取该账号所属机构
  static const String SEARCH_COMPANY_API =
     ServerApi.BASE_URL + "/app/appFindCompanyList";

  final String gps;


  ValueNotifier<PlaceHolderStatusType> statusValueNotifier;
  ValueNotifier<CompanyDetailDataBean> groupInfoValueNotifier;
  ValueNotifier<CompanyBasicInfoBean> groupInfoCompanyBasic;
  ValueNotifier<CompanySwitchListBean> companyValueNotifier;
  final VoidCallback onRefresh;
  Function _refresh;
  final CompanyDetailPageState state;
  ValueNotifier<List<OrgInfoListBean>> valueNotifier;

  CompanyDetailViewModel(this.state, this.onRefresh, this.gps) : super(state) {
    groupInfoValueNotifier = ValueNotifier(null);
    groupInfoCompanyBasic = ValueNotifier(null);
    companyValueNotifier = ValueNotifier(null);
    valueNotifier = ValueNotifier(null);
    statusValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    //监听顶部信息刷新
    _refresh = (event) {
      if (event is RefreshCompanyDetailPageEvent ||
          event is PersonDetailGroupRefreshEvent ||
          event is MultiDelegeRefreshEvent) {
        print('刷新顶部信息：${event.toString()}');
        getTopInfoHttp();
        getCompanyTopInfoHttp();
      }
    };
    VgEventBus.global.streamController.stream.listen(_refresh);
  }

  @override
  void onDisposed() {
    super.onDisposed();
    groupInfoValueNotifier?.dispose();
    statusValueNotifier?.dispose();
    groupInfoCompanyBasic?.dispose();
    companyValueNotifier?.dispose();
    _refresh = null;
  }

  ///获取顶部信息请求
  void getCompanyTopInfoHttp() {
    final String authId = UserRepository.getInstance().authId ?? "";
    if (authId == null || authId.isEmpty) {
      return;
    }
    if (isStateDisposed) {
      return;
    }

    VgHttpUtils.get(TOP_COMPANY_INFO_API,
        params: {
          "authId": authId ?? "",
          "gps":gps??""
        },
        callback: BaseCallback(onSuccess: (val) {
          IndependentCompanyBasicInfoBean bean =
              IndependentCompanyBasicInfoBean.fromMap(val);
          if (bean != null && bean?.data?.companyBasicInfo != null) {
            CacheUtil.putCache(TOP_COMPANY_INFO_API, bean.toJson());
          }
          groupInfoCompanyBasic?.value = bean?.data?.companyBasicInfo;
        }, onError: (msg) {
            VgToastUtils.toast(AppMain.context, "网络连接不可用");
          // statusValueNotifier.value = PlaceHolderStatusType.error;
        }));
  }

  ///查询切换列表数据
  void queryCompanyListData(BuildContext context) {
    VgHttpUtils.get(SEARCH_COMPANY_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "phone": UserRepository.getInstance().getPhone() ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          CompanySwitchListBean bean = CompanySwitchListBean.fromMap(val);
          companyValueNotifier?.value = bean;
        }, onError: (msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

  ///获取顶部信息缓存
  void getTopInfoCache() {
    CacheUtil.getCache(TOP_GROUP_INFO_API).then((value) {
      if (value != null) {
        print('加载缓存:$TOP_GROUP_INFO_API');
        CompanyDetailDataBean data = CompanyDetailDataBean.fromMap(value);
        statusValueNotifier.value = null;
        data.isCache = true;
        groupInfoValueNotifier?.value = data;
      }
    });
    CacheUtil.getCache(TOP_COMPANY_INFO_API).then((value) {
      if (value != null) {
        print('加载缓存');
        IndependentCompanyBasicInfoBean data =
            IndependentCompanyBasicInfoBean.fromMap(value);
        groupInfoCompanyBasic?.value = data?.data?.companyBasicInfo;
      }
    });
  }

  ///获取顶部信息请求
  ///fromPullRefresh 如果是true，不需要holder来展示加载过程
  void getTopInfoHttp({bool fromPullRefresh}) {
    final String authId = UserRepository.getInstance().authId ?? "";
    if (authId == null || authId.isEmpty) {
      return;
    }
    if (isStateDisposed) {
      return;
    }

    VgHttpUtils.get(TOP_GROUP_INFO_API,
        params: {
          "authId": authId ?? "",
          "searchOthers": state
                  ?.filterNotification?.companyDetailFilterValueNotifier?.value
                  ?.getParamsStr() ??
              "",
        },
        callback: BaseCallback(onSuccess: (val) {
          CompanyDetailResponseBean bean =
              CompanyDetailResponseBean.fromMap(val);
          if (!_compareTwoGroupListEqueal(bean?.data?.groupPersonCnt,
              groupInfoValueNotifier?.value?.groupPersonCnt)) {
            onRefresh?.call();
          }
          if(!(fromPullRefresh??false)){
            statusValueNotifier.value = null;
          }
          CompanyDetailDataBean companyDetailDataBean = bean?.data;
          if (companyDetailDataBean != null) {
            CacheUtil.putCache(
                TOP_GROUP_INFO_API, companyDetailDataBean.toJson());
            // UserRepository.getInstance()
            //     .userData
            //     .companyInfo
            //     .update(companyDetailDataBean.companyInfo.toJson());
            ///缓存班部门数
            SharePreferenceUtil.putInt(KEY_DEPARTMENT_CNT + UserRepository.getInstance().getCompanyId() ??'',companyDetailDataBean?.topCnt?.departmentCnt??0);
            SharePreferenceUtil.putInt(KEY_CLASS_CNT + UserRepository.getInstance().getCompanyId() ??'',companyDetailDataBean?.topCnt?.classCnt??0);

          }
          if(!isStateDisposed){
            groupInfoValueNotifier?.value = bean?.data;
          }

        }, onError: (msg) {
            VgToastUtils.toast(AppMain.context, "网络连接不可用");
          // VgToastUtils.toast(AppMain.context, msg);
          // statusValueNotifier.value = PlaceHolderStatusType.error;
        }));
  }

  ///比较两个列表内容是否完全相同
  bool _compareTwoGroupListEqueal(
      List<GroupPersonCntBean> newList, List<GroupPersonCntBean> oldList) {
    if ((newList == null || newList.isEmpty) ||
        (oldList == null || oldList.isEmpty)) {
      return true;
    }
    if (newList.length != oldList.length) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      if ((newList.elementAt(i)?.groupid != oldList.elementAt(i)?.groupid) || (newList.elementAt(i)?.cnt != oldList.elementAt(i)?.cnt)) {
        return false;
      }
    }
    return true;
  }

  ///获取该账号一起学机构
  void searchOrganization(
      BuildContext context, String phone) {
    if (phone == null || phone == "") {
      return;
    }
    if(phone.length != DEFAULT_PHONE_LENGTH_LIMIT){
      return;
    }
    VgHttpUtils.get(SEARCH_ORGANIZATION_API,
        params: {
          "phone": globalSubPhone(phone) ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          LoginSearchOrganizationBean bean = LoginSearchOrganizationBean.fromMap(val);
          if((bean?.data?.orgInfoList?.length??0)!=0){
            valueNotifier?.value = val = bean?.data?.orgInfoList;
          }
        }, onError: (msg) {

        }));
  }
}
